package org.androidpn.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import org.androidpn.R;
import org.androidpn.activity.MainActivity;
import org.androidpn.activity.TalkingActivity;
import org.androidpn.adapter.SortGroupMemberAdapter;
import org.androidpn.http.HttpApi;
import org.androidpn.model.CTalkList;
import org.androidpn.model.CUserInfo;
import org.androidpn.model.NetModel;
import org.androidpn.utils.ConstanceUtil;
import org.androidpn.utils.JsonUtil;
import org.androidpn.utils.ToastUtil;
import org.androidpn.widget.CharacterParser;
import org.androidpn.widget.ClearEditText;
import org.androidpn.widget.PinyinComparator;
import org.androidpn.widget.SideBar;
import org.androidpn.widget.SideBar.OnTouchingLetterChangedListener;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment2 extends Fragment implements OnClickListener {

	private CUserInfo cUserInfo;
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private SortGroupMemberAdapter adapter;
	private ClearEditText mClearEditText;

	private LinearLayout titleLayout;
	private TextView title;
	private TextView tvNofriends;
	/**
	 * 上次第一个可见元素，用于滚动时记录标识。
	 */
	private int lastFirstVisibleItem = -1;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<CUserInfo> sourceDateList = new ArrayList<CUserInfo>();

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	public Fragment2() {
		// Required empty public constructor
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_add_friends, container, false);
		initViews(view);
		MyResponseListener myResponseListener = new MyResponseListener();
		HttpApi.getFriendList(((MainActivity) getActivity()).cUserInfo.getTelephone(), myResponseListener,
				myResponseListener);
		cUserInfo = ((MainActivity) getActivity()).cUserInfo;
		sortListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				// TODO Auto-generated method stub
				 AlertDialog.Builder builder = new AlertDialog.Builder(Fragment2.this.getActivity());  
			        builder.setTitle("删除联系人？");  
			        final CUserInfo friend = ((CUserInfo) adapter.getItem(arg2));
			        builder.setPositiveButton("确定",  
			                new DialogInterface.OnClickListener() {  
			                    public void onClick(DialogInterface dialog, int whichButton) {
			                    	DeleteUserinfoListener deleteUserinfoListener =new DeleteUserinfoListener(arg2);
			                    	HttpApi.deleteFriend(cUserInfo.getTelephone(), friend.getTelephone(), deleteUserinfoListener, deleteUserinfoListener);
			                    }  
			                });  
			        builder.setNegativeButton("取消",  
			                new DialogInterface.OnClickListener() {  
			                    public void onClick(DialogInterface dialog, int whichButton) {
			                    	
			                    }  
			                });  
			        builder.show();  
				return true;
			}
		
		});
		return view;
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.search_ly:

			break;
		}
	}

	private void initViews(View view) {

		titleLayout = (LinearLayout) view.findViewById(R.id.title_layout);
		title = (TextView) view.findViewById(R.id.title_layout_catalog);
		tvNofriends = (TextView) view.findViewById(R.id.title_layout_no_friends);
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();

		sideBar = (SideBar) view.findViewById(R.id.sidrbar);
		dialog = (TextView) view.findViewById(R.id.dialog);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}

			}
		});

		sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				// ToastUtil.showShortToast(getActivity(),
				// ((CUserInfo)adapter.getItem(position)).getName());
				CUserInfo friend = ((CUserInfo) adapter.getItem(position));
				CTalkList cTalkList = new CTalkList();
				cTalkList.setFriend_icon(friend.getIcon());
				cTalkList.setFriend_name(friend.getName());
				cTalkList.setFriend_telephone(friend.getTelephone());
				cTalkList.setMy_icon(((MainActivity) getActivity()).cUserInfo.getIcon());
				cTalkList.setMy_name(((MainActivity) getActivity()).cUserInfo.getName());
				cTalkList.setMy_telephone(((MainActivity) getActivity()).cUserInfo.getTelephone());
				SetTalkRequestListener setTalkRequestListener = new SetTalkRequestListener();
				HttpApi.setTalkList(cTalkList, setTalkRequestListener, setTalkRequestListener);

				Intent intent = new Intent(getActivity(), TalkingActivity.class);
				intent.putExtra("ctalklist", cTalkList);
				startActivity(intent);
			}
		});

		// SourceDateList =
		// filledData(getResources().getStringArray(R.array.date));

		adapter = new SortGroupMemberAdapter(Fragment2.this.getActivity(), sourceDateList);
		sortListView.setAdapter(adapter);
		sortListView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

				// int section = getSectionForPosition(firstVisibleItem);
				// int nextSection = getSectionForPosition(firstVisibleItem +
				// 1);
				// int nextSecPosition = getPositionForSection(+nextSection);
				// if (firstVisibleItem != lastFirstVisibleItem) {
				// MarginLayoutParams params = (MarginLayoutParams) titleLayout
				// .getLayoutParams();
				// params.topMargin = 0;
				// titleLayout.setLayoutParams(params);
				// title.setText(sourceDateList.get(
				// getPositionForSection(section)).getSortLetters());
				// }
				// if (nextSecPosition == firstVisibleItem + 1) {
				// View childView = view.getChildAt(0);
				// if (childView != null) {
				// int titleHeight = titleLayout.getHeight();
				// int bottom = childView.getBottom();
				// MarginLayoutParams params = (MarginLayoutParams) titleLayout
				// .getLayoutParams();
				// if (bottom < titleHeight) {
				// float pushedDistance = bottom - titleHeight;
				// params.topMargin = (int) pushedDistance;
				// titleLayout.setLayoutParams(params);
				// } else {.,
				// if (params.topMargin != 0) {
				// params.topMargin = 0;
				// titleLayout.setLayoutParams(params);
				// }
				// }
				// }
				// }
				// lastFirstVisibleItem = firstVisibleItem;
			}
		});
		mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);

		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// 这个时候不需要挤压效果 就把他隐藏掉
				titleLayout.setVisibility(View.GONE);
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private void filledData(List<CUserInfo> mSortList) {

		for (int i = 0; i < mSortList.size(); i++) {
			// GroupMemberBean sortModel = new GroupMemberBean();
			// sortModel.setName(date[i]);
			// 汉字转换成拼音
			String pinyin = characterParser.getSelling(mSortList.get(i).getName());
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				mSortList.get(i).setSortLetters(sortString.toUpperCase());
			} else {
				mSortList.get(i).setSortLetters("#");
			}
		}
		// return mSortList;
	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<CUserInfo> filterDateList = new ArrayList<CUserInfo>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = sourceDateList;
			tvNofriends.setVisibility(View.GONE);
		} else {
			filterDateList.clear();
			for (CUserInfo sortModel : sourceDateList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}
		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
		if (filterDateList.size() == 0) {
			tvNofriends.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 根据ListView的当前位置获取分类的首字母的Char ascii值
	 */
	public int getSectionForPosition(int position) {
		if (sourceDateList != null && sourceDateList.get(position) != null) {
			return sourceDateList.get(position).getSortLetters().charAt(0);
		} else {
			return 0;
		}
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < sourceDateList.size(); i++) {
			String sortStr = sourceDateList.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}
		return -1;
	}

	class MyResponseListener
			implements com.android.volley.Response.Listener<String>, com.android.volley.Response.ErrorListener {

		@Override
		public void onErrorResponse(VolleyError error) {
		}

		@Override
		public void onResponse(String response) {
			// TODO Auto-generated method stub
			NetModel netModel = JsonUtil.parseObject(response, NetModel.class);
			if (netModel.getCode() == ConstanceUtil.REQUEST_SUCCESS) {
				sourceDateList = JsonUtil.parseArray(netModel.getContent(), CUserInfo.class);
				// 根据a-z进行排序源数据
				filledData(sourceDateList);
				Collections.sort(sourceDateList, pinyinComparator);
				adapter.updateListView(sourceDateList);
			} else {
				ToastUtil.showShortToast(getActivity(), netModel.getContent());
			}
		}

	}

	class SetTalkRequestListener
			implements com.android.volley.Response.Listener<String>, com.android.volley.Response.ErrorListener {

		@Override
		public void onErrorResponse(VolleyError error) {
		}

		@Override
		public void onResponse(String response) {
			// TODO Auto-generated method stub
			NetModel netModel = JsonUtil.parseObject(response, NetModel.class);
			if (netModel.getCode() == ConstanceUtil.REQUEST_SUCCESS) {
			} else {
			}
		}

	}
 class DeleteUserinfoListener implements Listener<String>,ErrorListener{
    private int position;
    public DeleteUserinfoListener(int position){
    	this.position =position;
    }
	public int getPosition() {
		return position;
	}

	public void setPosition(int position) {
		this.position = position;
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onResponse(String response) {
		// TODO Auto-generated method stub
		NetModel netModel =JsonUtil.parseObject(response, NetModel.class);
		if(netModel.getCode() ==ConstanceUtil.REQUEST_SUCCESS){
			sourceDateList.remove(position);
			adapter.notifyDataSetChanged();
			ToastUtil.showShortToast(Fragment2.this.getActivity(), netModel.getContent());
		}
	}
	 
 }
}
